package com.shop.web;

import com.shop.entity.Address;
import com.shop.entity.User;
import com.shop.service.IAddressService;
import com.shop.service.impl.AddressServiceImpl;
import com.shop.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/address")
public class AddressServlet extends BaseServlet {

    private IAddressService addressService = new AddressServiceImpl();

    /**
     * 查询根据uid查询用户的所有收货地址并展示
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected String show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        List<Address> address = addressService.findAddressByUid(user.getUid());
        req.setAttribute("address",address);
        return "forward:/pages/order/self_info.jsp";
    }


    /**
     * 修改地址
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected String update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Address address = WebUtils.getBean(new Address(), req.getParameterMap());
        addressService.update(address);
        return "redirect:/address?method=show";
    }

    /**
     * 添加收货地址
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Address address = WebUtils.getBean(new Address(), req.getParameterMap());
        addressService.add(address);
        return "redirect:/address?method=show";
    }

    /**
     * 删除收货地址
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected String delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int aid = WebUtils.parseInt(req.getParameter("aid"), 0);
        addressService.delete(aid);
        return "redirect:/address?method=show";
    }

    /**
     * 设置默认地址
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected String setDefault(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int aid = WebUtils.parseInt(req.getParameter("aid"), 0);
        User user = (User) req.getSession().getAttribute("user");
        addressService.setDefault(aid,user.getUid());
        return "redirect:/address?method=show";
    }
}
